import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { login as loginApi, getCurrentAdmin, logout as logoutApi } from '@/api/auth'

const initialState = {
  userInfo: null,
  token: localStorage.getItem('token') || null,
  loading: false,
  error: null,
}

// 异步登录
export const login = createAsyncThunk(
  'user/login',
  async (credentials, { rejectWithValue }) => {
    try {
      const data = await loginApi(credentials)
      return data
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

// 获取当前管理员信息
export const fetchUserInfo = createAsyncThunk(
  'user/fetchUserInfo',
  async (_, { rejectWithValue }) => {
    try {
      const data = await getCurrentAdmin()
      return data
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

// 退出登录
export const logoutAsync = createAsyncThunk(
  'user/logout',
  async (_, { rejectWithValue }) => {
    try {
      await logoutApi()
      return true
    } catch (error) {
      return rejectWithValue(error.response?.data || error.message)
    }
  }
)

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setToken: (state, action) => {
      state.token = action.payload
      if (action.payload) {
        localStorage.setItem('token', action.payload)
      } else {
        localStorage.removeItem('token')
      }
    },
    setUserInfo: (state, action) => {
      state.userInfo = action.payload
    },
    logout: (state) => {
      state.userInfo = null
      state.token = null
      localStorage.removeItem('token')
    },
    clearError: (state) => {
      state.error = null
    },
  },
  extraReducers: (builder) => {
    builder
      // 登录
      .addCase(login.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(login.fulfilled, (state, action) => {
        state.loading = false
        const data = action.payload.data || action.payload
        state.token = data.token
        state.userInfo = data.user
        localStorage.setItem('token', data.token)
      })
      .addCase(login.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload
      })
      // 获取用户信息
      .addCase(fetchUserInfo.pending, (state) => {
        state.loading = true
      })
      .addCase(fetchUserInfo.fulfilled, (state, action) => {
        state.loading = false
        state.userInfo = action.payload.data || action.payload
      })
      .addCase(fetchUserInfo.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload
      })
      // 退出登录
      .addCase(logoutAsync.pending, (state) => {
        state.loading = true
      })
      .addCase(logoutAsync.fulfilled, (state) => {
        state.loading = false
        state.userInfo = null
        state.token = null
        localStorage.removeItem('token')
      })
      .addCase(logoutAsync.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload
        // 即使退出失败也清除本地数据
        state.userInfo = null
        state.token = null
        localStorage.removeItem('token')
      })
  },
})

export const { setToken, setUserInfo, logout, clearError } = userSlice.actions
export default userSlice.reducer
